
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
 
import os
import io
import pandas as pd
import re
# 如果本身就是tf1，直接导入即可
import tensorflow.compat.v1 as tf
from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple
 
flags = tf.app.flags
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS


# 将分类名称转成ID号，根据自己实际打的标签进行修改
def class_text_to_int(row_label):
    if row_label == 'crack':
        return 1
    elif row_label == 'positive':
        return 1
    elif row_label == 'negative':
        return 2
    elif row_label == 'D00':
        return 1
    elif row_label == 'D10':
        return 2
    elif row_label == 'D20':
        return 3
    elif row_label == 'D40':
        return 4
    elif row_label == 'Repair':
        return 5
    else:
        # 其他都归为一类
        return 99
 
 
def split(df, group):
    data = namedtuple('data', ['filename', 'object'])
    gb = df.groupby(group)
    return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
 
 
def create_tf_example(group, path):
    dir_path = path
    # if re.match(r'(.*)_(.*?)', group.filename, re.M|re.I):
    #     dir_path = path + '/positive'
    # else:
    #     dir_path = path + '/positive'
    print(os.path.join(dir_path, '{}'.format(group.filename)))
    with tf.gfile.GFile(os.path.join(dir_path, '{}'.format(group.filename)), 'rb') as fid:
        encoded_jpg = fid.read()
    encoded_jpg_io = io.BytesIO(encoded_jpg)
    image = Image.open(encoded_jpg_io)
    width, height = image.size
 
    filename = (group.filename + '.jpg').encode('utf8')
    image_format = b'jpg'
    xmins = []
    xmaxs = []
    ymins = []
    ymaxs = []
    classes_text = []
    classes = []
 
    for index, row in group.object.iterrows():
        xmins.append(row['xmin'] / width)
        xmaxs.append(row['xmax'] / width)
        ymins.append(row['ymin'] / height)
        ymaxs.append(row['ymax'] / height)
        classes_text.append(row['class'].encode('utf8'))
        classes.append(class_text_to_int(row['class']))
 
    tf_example = tf.train.Example(features=tf.train.Features(feature={
        'image/height': dataset_util.int64_feature(height),
        'image/width': dataset_util.int64_feature(width),
        'image/filename': dataset_util.bytes_feature(filename),
        'image/source_id': dataset_util.bytes_feature(filename),
        'image/encoded': dataset_util.bytes_feature(encoded_jpg),
        'image/format': dataset_util.bytes_feature(image_format),
        'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
        'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
        'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
        'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
        'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
        'image/object/class/label': dataset_util.int64_list_feature(classes),
    }))
    return tf_example

def write_to_file (csv_input, imgPath, writer):
    examples = pd.read_csv(csv_input)
    path = imgPath
    grouped = split(examples, 'filename')
    for group in grouped:
        tf_example = create_tf_example(group, path)
        writer.write(tf_example.SerializeToString())
 
def main(csv_input, imgPath, output_path):
    writer = tf.python_io.TFRecordWriter(output_path)
    if isinstance(csv_input, list):
        for item in csv_input:
            write_to_file(item["csv_input"], item["imgPath"], writer)
    else:
        write_to_file(csv_input, imgPath, writer)
    writer.close()


if __name__ == '__main__':
    # 生成训练集
    # csv_input = '../data/train.csv'
    # trainImgPath = '../images/train'
    # output_path = '../tf_record/train.record'
    # main(csv_input, trainImgPath, output_path)
 
    # 生成验证集
    # csv_input = '../data/eval.csv'
    # evalImgPath = '../images/eval'
    # output_path = '../tf_record/eval.record'
    # main(csv_input, evalImgPath, output_path)

    # 生成训练集
    # csv_input = '../dataset/China_MotorBike/train.csv'
    # trainImgPath = '../dataset/China_MotorBike/train/images'
    # output_path = '../tf_record/train.tfrecord'
    # main(csv_input, trainImgPath, output_path)
 
    # 生成验证集
    # csv_input = '../dataset/China_MotorBike/eval.csv'
    # evalImgPath = '../dataset/China_MotorBike/train/images'
    # output_path = '../tf_record/eval.tfrecord'
    # main(csv_input, evalImgPath, output_path)

    # 生成训练集
    trains = [
        {"csv_input": '../dataset/RDD_China/China_Drone/train.csv', "imgPath": '../dataset/RDD_China/China_Drone/train/images'},
        {"csv_input": '../dataset/RDD_China/China_MotorBike/train.csv', "imgPath": '../dataset/RDD_China/China_MotorBike/train/images'}
    ]
    output_path = '../tf_record/train.tfrecord'
    main(trains, None, output_path)
 
    # 生成验证集
    evals = [
        {"csv_input": '../dataset/RDD_China/China_Drone/eval.csv', "imgPath": '../dataset/RDD_China/China_Drone/train/images'},
        {"csv_input": '../dataset/RDD_China/China_MotorBike/eval.csv', "imgPath": '../dataset/RDD_China/China_MotorBike/train/images'}
    ]
    output_path = '../tf_record/eval.tfrecord'
    main(trains, None, output_path)